//
//  FRPPhotoImporter.m
//  FunctionalReactivePixels
//
//  Created by Ran on 15/9/6.
//  Copyright (c) 2015年 gintong. All rights reserved.
//

#import "FRPPhotoImporter.h"
#import "FRPPhotoModel.h"

@implementation FRPPhotoImporter

+ (RACSignal *)importPhotos
{
    RACReplaySubject *subject = [RACReplaySubject subject];
    
    NSURLRequest *request = [self popularUrlRequest];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data) {
            id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            [subject sendNext:[[[results[@"m"] rac_sequence] map:^id(NSDictionary *dic) {

                FRPPhotoModel *model = [FRPPhotoModel new];
                [self configurePhotoModel:model withDictionary:dic];
                [self downloadImageForModel:model];
                return model;
                
            }] array]];
            [subject sendCompleted];
        }else{
            [subject sendError:connectionError];
        }
        
    }];
    
    return subject;
    
}

+ (NSURLRequest *)popularUrlRequest{
    return [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a.54whr.com/Mcdonald/GetV2"]];
    return nil;
}
        
+ (void)configurePhotoModel: (FRPPhotoModel *)model withDictionary: (NSDictionary *)dictionary{

    model.i = dictionary[@"i"];
    model.l = dictionary[@"l"];
    model.t = dictionary[@"t"];
    model.p = [dictionary[@"p"] floatValue];
    model.s = [dictionary[@"s"] floatValue];
    model.h = [dictionary[@"h"] floatValue];
    model.c = dictionary[@"c"];
    
}

+ (void)downloadImageForModel: (FRPPhotoModel *)model{
    
    NSAssert(model.i, @"not nil is required");
    
//    [self download:model.i withCompletion:^(NSData *data) {
//        model.imageData = data;
//    }];
    
    RAC(model, imageData) = [self download:model.i];
}

+ (RACSignal *)download: (NSString *)urlString{

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    return [[[NSURLConnection rac_sendAsynchronousRequest:request] map:^id(RACTuple *value) {
        return [value second];
    }] deliverOn:[RACScheduler mainThreadScheduler]];
    
}

+ (void)download: (NSString *)urlString withCompletion: (void(^)(NSData *data))completion{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (completion) {
            completion(data);
        }
    }];
    
}

@end
